package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IStoryService;
import com.ruoyi.system.service.StorySysEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class StoryServiceImpl implements IStoryService {

    @Autowired
    private StoryMapper storyMapper;

    @Autowired
    private QueClassificationMapper queClassificationMapper;

    @Autowired
    private SysStudentMapper sysStudentMapper;

    @Autowired
    private SysEmployeeMapper sysEmployeeMapper;

    @Autowired
    private TaskServiceImpl taskService;

    @Autowired
    private StorySysEmployeeService storySysEmployeeService;

    @Autowired
    private StorySysEmployeeMapper storySysEmployeeMapper;

    @Override
    public String getStuImByKeyId(String keyId){
        return sysEmployeeMapper.getStuByKeyId(keyId);
    }

    @Override
    public String getEmpImByKeyId(String keyId){
        return sysEmployeeMapper.getImByKeyId(keyId);
    }

    @Override
    public int getStudentIdById(int id){
        return storyMapper.getStudentIdById(id);
    }



    @Override
    public boolean insertStory(Story story) {
        int result = storyMapper.insertStory(story);
        if(result > 0) {
            return true;
        }
        return false;
    }


    @Override
    public List<Story> selectStoryList(String studentId, String classID, String departmentID, String beginTime, String endTime) throws Exception {
        String flag = studentId + classID + departmentID;
        List<Story> list = null;
        if (StringUtils.isEmpty(flag)){


            if (StringUtils.isNotEmpty(beginTime)){  //当开始时间不为空时，才需要用时间去过滤
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                if (StringUtils.isEmpty(endTime)) //如果没有传入结束时间就默认是今天
                {
                    Date now = new Date();
                    endTime = format.format(now);
                }
                list = storyMapper.selectStoryListByTime(beginTime, endTime);

            }else {
                list = storyMapper.selectStoryList();
            }

        }else if (StringUtils.isNotEmpty(studentId)){
            list = storyMapper.selectStoryListByStudentId(studentId);
        }else if (StringUtils.isNotEmpty(classID)){
            list = storyMapper.selectStoryListByClassID(classID);
        }else{
            list = storyMapper.selectStoryListByDepartmentID(departmentID);
        }


        return list;

    }

    @Override
    public Story selectStoryById(Long id) {
        return storyMapper.selectStoryById(id);
    }

    @Override
    public int deleteStoryByIds(String ids) {
        Long[] storyIds = Convert.toLongArray(ids);
//        for (Long id : postIds)
//        {
//            Story story = selectStoryById(id);
////            if (countUserPostById(postId) > 0)
////            {
////                throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName()));
////            }
//        }
        return storyMapper.deleteStoryByIds(storyIds);
    }

    @Override
    public int deleteStorySByIds(String ids) {
        Long[] storyIds = Convert.toLongArray(ids);
        return storyMapper.deleteStorySByIds(storyIds);
    }

    @Override
    public int deleteMessageByIds(String ids) {
        Long[] storyIds = Convert.toLongArray(ids);
        return storyMapper.deleteMessageByIds(storyIds);
    }

    public Story selectStateById(int id){
        return storyMapper.selectStateById(id);
    }


    @Override
    public int updateHandleStateAndHandleTime(int id, int handleState, String opinion) {
        String handleTime = null;
        int count = 0;
        if (handleState == 0){  //0表示是未受理状态，则需要++变成受理状态也就是未审核状态
            handleState++;
            //添加当前时间
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            handleTime = dateFormat.format(now);//格式化然后放入字符串中

            System.out.println(id + "--------" + handleState + "--------" + handleTime);

            count = storyMapper.updateHandleStateAndHandleTime(id, handleState, handleTime);
        }else if (handleState == 1 || handleState == 3 || handleState == 4 || handleState == 5 || handleState == 6){
            handleState++;
            count = storyMapper.updateHandleState(id, handleState);
        }else if(handleState == 8 || handleState == 9 || handleState == 10){
//            handleState = 11;
            String otherTime = storyMapper.selectHandleTimeById(id);
            handleTime = otherTime;
            //查询出其他状态的时间然后用，拼接
            //添加当前时间
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            handleTime = dateFormat.format(now);//格式化然后放入字符串中
            Date opinionTime = null;
            try {
                opinionTime = dateFormat.parse( handleTime );
            } catch (ParseException e) {
                e.printStackTrace();
            }

            handleTime = otherTime + "," + handleTime;
            if (StringUtils.isEmpty(opinion))
                count = storyMapper.updateHandleStateAndHandleTime(id, handleState, handleTime);
            else
                count = storyMapper.updateHandleStateAndHandleTimeAndOpinion(id, handleState, handleTime, opinion, opinionTime);
        }


        //更新状态需要去提醒学生
//        taskService.send(sysEmployeeMapper.getStuByKeyId(String.valueOf(id)), "progressUpdate");
//        taskService.send(getStuImByKeyId(String.valueOf(id)), "progressUpdate");8



        return count;
    }



    @Override
    public int updateHandleStateByCompletion(int id, int handleState) {
        String handleTime = null;
        if (handleState == 3){
            handleState = 8;
        }else if(handleState == 6){
            handleState = 9;
        }
        else if(handleState == 7){
            handleState = 10;
        }

        //更新状态需要去提醒学生
//        taskService.send(sysEmployeeMapper.getStuByKeyId(String.valueOf(id)), "progressUpdate");
//        taskService.send(getStuImByKeyId(String.valueOf(id)), "progressUpdate");
//        //查询出其他状态的时间然后用，拼接
//        String otherTime = storyMapper.selectHandleTimeById(id);
//        //添加当前时间
//        Date now = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//设置日期格式
//        handleTime = dateFormat.format(now);//格式化然后放入字符串中
//        handleTime = otherTime + "," + handleTime;
        return storyMapper.updateHandleState(id, handleState);
    }

    @Override
    public int invalidHandleState(int id) {
        return storyMapper.invalidHandleState(id);
    }

    @Override
    public int updateClassId(int id, int classId) {
        return storyMapper.updateClassId(id, classId);
    }

    @Override
    public boolean updateStatusCount(int id) {
        int result = storyMapper.updateStatusCount(id);
        if(result > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updateMychatcountZero(int id) {
        int result = storyMapper.updateMychatcountZero(id);
        if(result > 0) {
            return true;
        }
        return false;
    }

    @Override
    public int selectSumChatCount() {
        return storyMapper.selectSumChatCount();
    }

    @Override
    public List<Story> selectStroyListByStudentId(int studentId) {
        return storyMapper.selectStroyListByStudentId(studentId);
    }

    @Override
    public List<QueClassification> selectClassById(int id) {
        int classId = storyMapper.selectClassById(id);
        if (classId == 0){
            return queClassificationMapper.selectClassList();
        }else {
            return Arrays.asList(queClassificationMapper.selectClassNameById(classId));
        }
    }

    @Override
    public int updateOpinion(int id, String opinion)  {
        //添加当前时间
//        Date now = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//        String time = dateFormat.format(now);//格式化然后放入字符串中


        Date date = new Date();//获得系统时间.
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        String nowTime = sdf.format(date);
        Date time = null;
        try {
            time = sdf.parse( nowTime );
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int index = storyMapper.updateOpinion(id, opinion, time);
        return index;
    }

    @Override
    public Story selectStoryOpinion(int storyId){
        return storyMapper.selectStoryOpinion(storyId);
    }

    @Override
    public int updateIsForcedSubmitByIdAndHandleState(int storyId, int forcedSubmitOrder) {

        int isSuccess = storyMapper.updateHandleState(storyId, 7);
        if (isSuccess == 1){
            //添加当前时间
            Date now = new Date();
            storyMapper.updateIsForcedSubmitById(storyId, forcedSubmitOrder, now);
        }

        return 0;
    }

    @Override
    public String selectForcedSubmitTime(int storyId) {
        Date date = storyMapper.selectForcedSubmitTime(storyId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String forcedSubmitTime = sdf.format(date);
        return forcedSubmitTime;
    }

    @Override
    public List<ExportStory> exportStory(String ids) {
        List<ExportStory> list = new ArrayList<>();


        Long[] storyIds = Convert.toLongArray(ids);


        List<Story> storyList = storyMapper.selectStorys(storyIds);
        for (Story story : storyList) {
            ExportStory exportStory = new ExportStory();
            exportStory.setId(story.getId());



            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf.format(story.getDate());
            exportStory.setDate(date);

            exportStory.setProblem(story.getProblem());

            exportStory.setProgramme(story.getProgramme());

            exportStory.setRemarks(story.getRemarks());

            System.out.println(story.getHandleState());
            if (story.getHandleState() == -1){
                exportStory.setTransactionClass("无效");
            }else if (story.getHandleState() == 0 || story.getHandleState() == 1){

            } else {
                QueClassification queClassification = queClassificationMapper.selectClassNameById(story.getClassId());
                System.out.println(queClassification.getClassName());
                exportStory.setTransactionClass(queClassification.getClassName());

                List<StorySysEmployee> storySysEmployees = storySysEmployeeMapper.selectEmpsByStorytId(story.getId());
                if (storySysEmployees.size() == 0){
                    //什么都不做
                }else {
                    String firstDepartmentName = "";
                    String firstReply = "";
                    String secondDepartmentName = "";
                    String secondReply = "";
                    for (StorySysEmployee storySysEmployee : storySysEmployees) {
                        if (storySysEmployee.getTransferNumber() == 1){
                            exportStory.setFirstOpinion(storySysEmployee.getOpinion());
                            firstDepartmentName += storySysEmployee.getDepartmentName() + "的" + storySysEmployee.getSysEmployeeName();
                            if(storySysEmployee.getReply() == null || storySysEmployee.getReply().length() == 0){
                                firstReply += "未答复";
                            }else {
                                firstReply += storySysEmployee.getReply();
                            }

                            if (storySysEmployees.size() > 1){
                                firstDepartmentName += "、";
                                firstReply += "、";
                            }
                        }else if (storySysEmployee.getTransferNumber() == 2){
                            exportStory.setSecondOpinion(storySysEmployee.getOpinion());
                            secondDepartmentName += storySysEmployee.getDepartmentName() + "的" + storySysEmployee.getSysEmployeeName();

                            if(storySysEmployee.getReply() == null || storySysEmployee.getReply().length() == 0){
                                secondReply += "未答复";
                            }else{
                                secondReply += storySysEmployee.getReply();
                            }

                            if (storySysEmployees.size() > 1){
                                secondDepartmentName += "、";
                                secondReply += "、";
                            }
                        }
                    }
                    if (storySysEmployees.size() > 1){
                        if(firstDepartmentName != "")
                            firstDepartmentName = firstDepartmentName.substring(0,firstDepartmentName.length()-1);
                        if(firstReply != "")
                            firstReply = firstReply.substring(0,firstReply.length()-1);
                        if(secondDepartmentName != "")
                            secondDepartmentName = secondDepartmentName.substring(0,secondDepartmentName.length()-1);
                        if(secondReply != "")
                            secondReply = secondReply.substring(0,secondReply.length()-1);
                    }
                    exportStory.setFirstTransferDepartmentName(firstDepartmentName);
                    exportStory.setFirstReply(firstReply);
                    exportStory.setSecondTransferDepartmentName(secondDepartmentName);
                    exportStory.setSecondReply(secondReply);
                }
            }


            if(story.getHandleState() >= 8){
                exportStory.setTransactionState("已完成");
            }else if (story.getHandleState() == 0){
                exportStory.setTransactionState("未处理");
            }else {
                exportStory.setTransactionState("处理中");
            }


            list.add(exportStory);
        }



        return list;
    }

}
